#include <iostream>
#include <string>
#include <cerrno>  // errno.h
#include <cstring> // string.h
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

const int size1 = 1024;

string getOtherMessage()
{
    // 获取pid和计数
    static int cnt = 0; // 作用域在本函数内有效，声明周期全局存在
    string messageid = to_string(cnt);
    cnt++;
    pid_t self_id = getpid();
    string stringpid = to_string(self_id);

    std::string message = "messageid: ";
    message += messageid;
    message += " my pid is : ";
    message += stringpid;

    return message;
}
// 子进程写入
void SubProcessWrite(int wfd)
{
    int pipesize = 0;
    std::string message = "father, I am your son prcess!";
    while (true)
    {
        string info = message + getOtherMessage();
        write(wfd, info.c_str(), info.size()); // 没有必要写入\0
        cerr << info << endl;
        // sleep(1); // 子进程写慢一点
        // write(wfd, &c, 1);
        // std::cout << "pipesize: " << ++pipesize << " write charator is : "<< c++ << std::endl;
        // // if(c == 'G') break;

        // sleep(1);
    }
    cout << "child quit..." << endl;
}
// 父进程读取
void FatherProcessRead(int rfd)
{
    while (true)
    {
        sleep(2);
        std::cout << "-------------------------------------------" << std::endl;
        char inbuffer[size1];
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer));
        if (n > 0)
        {
            inbuffer[n] = 0; // 手动添加"\0"
            cout << inbuffer << endl;
        }
        else if (n == 0)
        {
            // 表示写端直接关闭，读到文件结尾
            std::cout << "client quit, father get return val: " << n << " father quit too!" << std::endl;
            break;
        }
        else if (n < 0)
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }
}

int main()
{
    // 1.创建管道
    int pipefd[2];
    int n = pipe(pipefd); // 输出型参数
    if (n != 0)
    {
        cerr << "errno:" << errno << ":" << "errstring : " << strerror(errno) << std::endl;
        return 1;
    }
    // 0表示读，1表示写
    cout << "pipefd[0]" << pipefd[0] << ",pipefd[1]" << pipefd[1] << endl;

    // 2.创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        cout << "子进程发消息（写入）,关闭不需要fd" << endl;
        sleep(1);
        // 关闭不需要的fd
        close(pipefd[0]);
        // 准备写入
        SubProcessWrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    cout << "父进程读消息,关闭不需要fd" << endl;
    sleep(1);
    close(pipefd[1]);
    // 读消息
    FatherProcessRead(pipefd[0]);
    cout << "5s, father close rfd" << endl;
    sleep(5);
    close(pipefd[0]);
    // 等待回收
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if (rid > 0)
    {
        std::cout << "wait child process done, exit sig: " << (status & 0x7f) << std::endl;
        std::cout << "wait child process done, exit code(ign): " << ((status >> 8) & 0xFF) << std::endl;
    }
    return 0;
}